class ApplicationController < ActionController::Base
  
  before_filter :check_account, :except => [:login]
  before_filter :load_sections, :except => [:login]
  protect_from_forgery
    
  protected

  def current_account
    begin
      @current_account ||= Account.find session[:account_id]
    rescue ActiveRecord::RecordNotFound => e
      return nil
    end
    @current_account
  end

  def check_account
    unless current_account
      flash[:error] = "Ingrese al sistema primero"
      logger.warn "account is not connected, redirecting to AccountsController#login"
      redirect_to login_url
    end
  end

  def load_sections
    if @current_account
        if @current_account.admin
            @sections ||= Section.where(:parent_section_id => nil,:active => true).order(:section_order)
        else
            @sections ||= Section.where(:parent_section_id => nil,:user_only => true,:active => true).order(:section_order)
        end
    end
  end

end
